<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script>
    var socket;
    if (window.WebSocket) {
        //go on
        socket = new WebSocket("ws://localhost:7000/hello");
        //相当于channelRead,ev 收到服务器端回送的消息
        socket.onmessage = function (ev) {
            let rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + ev.data;
        }
        //相当于 链接开启（感知）
        socket.onopen = function (ev) {
            let rt = document.getElementById("responseText");
            rt.value = "链接开启了";
        }
        //相当于 链接关闭 （感知）
        socket.onclose = function (ev) {
            let rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "链接关闭了";
        }
    } else {
        alert("当前浏览器不支持WEBSOCKET");
    }

    //发送消息到服务器
    function send(message) {
        //判断socket链接是否创建好
        if (!window.socket) {
            return;
        }
        if (socket.readyState === WebSocket.OPEN) {
            //通过socket 发送消息
            socket.send(message);
        } else {
            alert("链接未背开启");
        }
    }
</script>
<body>
<form onsubmit="return false">
    <label>
        <textarea id="message" style="height: 300px;width: 300px"></textarea>
    </label>
    <input type="button" value="发生消息" onclick="send(this.form.message.value)">
    <label>
        <textarea id="responseText" style="height: 300px;width: 300px"></textarea>
    </label>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>